/**
 * 考勤信息列表attendList.js
 * 版本号： v1.0.0
 */
$(function(){
    //初始化年月
    iniTime();

});

//初始化日期天数
var dateSizeInit = 0;
function initData(){
    var prId = $('#prId').val();
    var rangeTime = $('#rangeTimeArg').val();
    //构建考勤表头
    var fieldArr = [];
    for(var i=1;i<=31;i++){
        var obj ={
            field: 'day' + i,
            title: i + '号' ,
            width:100,
            align:'center',
            fixed: true,
            formatter:function (value) {
                if(value){
                    return '<a href="#" style="display:block;height: 30px;width:100%;line-height: 2.5;" onMouseOver="toolTip(this,event,\''+value+'\')" onMouseOut="removeTooltip(this)">'+value+'</a>';
                }
            }
        };
        fieldArr.push(obj);
    }
    $("#attendStatistic_dataList").datagrid({
        fitColumns: true,
        fit:true,
        method: "POST",
        rownumbers: true,
        singleSelect:true,
        pagination: true,
        border: false,
        striped:true,
        pageSize:10,
        pageList:[10,50,100,500,1000],
        queryParams:{rangeTime:rangeTime},
        url: CONTEXT_PATH + '/attend/attendStatisticInfo.do?projectId=' + prId,
        idField: 'personName',
        frozenColumns:[[
            {field:'personName', title: '姓名', width: 70, align:'center',fixed: true},
            {field:'workType', title: '工种名称', width: 100, align:'center',fixed: true}
        ]],
        columns: [
            [{"title":"日期","colspan":31}],
            fieldArr
        ],
        onLoadSuccess:function(data){
            var dateSize = data.dateSize;
            if(dateSize > 0){
                dateSizeInit = dateSize;
                for(var i=29;i<=31;i++){
                    $('#attendStatistic_dataList').datagrid('showColumn', 'day' + i);
                    if(i > dateSize){
                        $('#attendStatistic_dataList').datagrid('hideColumn', 'day' + i);
                    }
                }
            }
        }
    });

    //定义可操作按钮
    $("#attendStatistic_menu").dialog({
        title: '',
        width: 'auto',
        height:35,
        closed: false,
        cache: false,
        inline: true,
        modal: false,
        border: false,
        toolbar: createToolbar()
    })
}

//初始化年月下拉
function iniTime(){
    //设置年下拉
    var themecombo = [];//创建年度数组
    var thisYear=new Date().getUTCFullYear();//今年
    var endYear=thisYear - 5;//结束年份
    for(var i=thisYear;i>=endYear;i--){
        themecombo.push({"text":i, "value": i});
    }
    $("#yearChoose").combobox("loadData", themecombo);//下拉框加载数据
    $("#yearChoose").combobox({
        onChange:function(){
            setTimeRegion();
        }
    });
    $("#yearChoose").combobox("setValue",thisYear);//设置默认值为今年

    //设置月下拉
    var themecomboMonth = [];//创建月份数组
    var startMonth = 1;
    var thisMonth=new Date().getUTCMonth()+1;//本月
    for(startMonth;startMonth<13;startMonth++){
        themecomboMonth.push({"text":startMonth, "value": startMonth});
    }
    $("#monthChoose").combobox("loadData", themecomboMonth);//下拉框加载数据
    $("#monthChoose").combobox({
        onChange:function(){
            setTimeRegion();
        }
    });
    $("#monthChoose").combobox("setValue",thisMonth);//设置默认值为本月
    //初始化数据表格
    initData();

}

//设置时间范围
function setTimeRegion() {
    var year = $("#yearChoose").combobox('getValue');
    var month =  $("#monthChoose").combobox('getValue');
    var d= new Date(year,month,0).getDate();
    var strMonth = getStrValue(month);
    var strDay = getStrValue(d);
    var region = year + "." + strMonth + ".01--" + year + "." + strMonth + "." + strDay;
    $("#rangeTime").text(region);
    var regionForArg = year + "-" + strMonth + "-01;" + year + "-" + strMonth + "-" + strDay;
    $("#rangeTimeArg").val(regionForArg);
}

/**
 * 创建toolbar按钮组
 * @returns {Array}
 */
function createToolbar() {
    var toolbar = [];
    var falg = false;
    for (var j = 0; j < btnOptions.length; j++) {
        if (false != btnOptions[j].value) {
            falg = true;
            break;
        }
    }
    if (!falg) {
        //不存在按钮
        toolbar.push({});
    } else {
        //存在按钮
        for (var i = 0; i < btnOptions.length; i++) {
            if (false != btnOptions[i].value) {
                //查询按钮
                if ("searchBtn" == btnOptions[i].key) {
                    toolbar.push({
                        id:btnOptions[i].value.meId,
                        text:btnOptions[i].value.name,
                        iconCls:btnOptions[i].value.iconCls,
                        handler:function(){
                            attendStatistic_findList();
                        }
                    });
                }
                //导出按钮
                if ("exportBtn" == btnOptions[i].key) {
                    toolbar.push({
                        id:btnOptions[i].value.meId,
                        text:btnOptions[i].value.name,
                        iconCls:btnOptions[i].value.iconCls,
                        handler:function(){
                            attendStatistic_export();
                        }
                    });
                }
            }
        }
    }
    return toolbar;
}

/**
 * 查询考勤统计信息
 */
function attendStatistic_findList(){
    //刷新dg页码
    refreshPageNumber("attendStatistic_dataList");
    $("#attendStatistic_dataList").datagrid("reload",{prId:$("#prId").val(),rangeTime:$("#rangeTimeArg").val(),personName:$("#personName").textbox("getValue")});
    //清除选中项
    $("#attendStatistic_dataList").datagrid("clearSelections");
}

/**
 * 鼠标移入弹出弹框
 * @param t 指当前对象，即超链接
 * @param e event事件
 * @param timeData 要显示的内容
 */
function toolTip(t,e,timeData){
    if(timeData){
        if( $('#tooltip').length == 0){
            var timeArr = timeData.split(",");
            var timeResult = "";
            //自适应增加高度
            var addHeight = "1";
            for(var i=0;i<timeArr.length;i++){
                timeResult = timeResult + timeArr[i]+"\n";
                if(i > 1){
                    addHeight = parseInt(addHeight) + 15;
                }
            }
            var texareaHeight = 30+parseInt(addHeight);
            var leftWidth = e.pageX;
            var topHeight = e.pageY;
            var bodyWidth = $('#easyuiLayoutId').width() -220;
            var bodyHeight = $('#easyuiLayoutId').height() - 180;
            var tooltipHtml = "<div id='tooltip' class='tooltip' onClick='removeTooltip(this)'>" +
                "<textarea style='height:"+texareaHeight + "px;width: 150px'>"+timeResult+"</textarea>" +
                "</div>";
            $(t).append(tooltipHtml); //添加到页面中
            if(topHeight > bodyHeight){
                topHeight =  topHeight - 200;
            }else{
                topHeight =  topHeight - 140;
            }
            if(leftWidth > bodyWidth){
                leftWidth =  leftWidth - 300;
            }else{
                leftWidth =  leftWidth - 100;
            }
            $("#tooltip").css({
                "top": topHeight + "px",
                "left": leftWidth + "px"
                /*"height":addHeight + "px"*/
            }).show("fast"); //设置提示框的坐标，并显示
        }
    }
}

/**
 * 移除本提示框
 */
function removeTooltip() {
    $("#tooltip").remove()
}

/**
 * 导出列表数据
 */
function attendStatistic_export(){
    //构建数据表的二维数组的DATA
    var sheetData = [];
    //每一行的数据
    var rowData = [];
    //从页面上的表格数据中获取到数据表格的所有数据，是一个二维数据结构
    var rows = $('#attendStatistic_dataList').datagrid("getRows");
    //数据列表为空，则不导出
    if(rows.length == 0){
        $.messager.show({ title:"操作提示", msg: "无数据可导出", timeout:3000, showType:"slide" });
        return;
    }
    //获取数据表中冻结的所有列
    var column = $('#attendStatistic_dataList').datagrid("options").columns[0];
    //获取数据表中未冻结的所有列
    var columns = $('#attendStatistic_dataList').datagrid("options").columns[1];
    //获取数据表中被冻结的所有列
    var frozenColumns = $('#attendStatistic_dataList').datagrid("options").frozenColumns[0];
    //设置列表头行（描述行）
    //首行增加标题
    var currYear = $("#yearChoose").combobox("getValue") + "年";
    var currMonth = $("#monthChoose").combobox("getValue") + "月";
    var title = $('#prName').val()+ currYear + currMonth + "考勤记录表";
    rowData.push(title);
    //将构建好的第一行描述列的数据放入二维数据表的二维数组中。
    sheetData.push(rowData);
    //行数据置空
    rowData = [];
    //加载被冻结的列名
    for (var i = 0; i < frozenColumns.length; i++) {
        if(frozenColumns[i].title){
            rowData.push(frozenColumns[i].title);
        }
    }
    //加载未被冻结的列名
    for (var i = 0; i < dateSizeInit ; i++) {
        if(i == 0){
            rowData.push(column[i].title);
        }else{
            rowData.push(null);
        }
    }
    //将构建好的第二行描述列的数据放入二维数据表的二维数组中。
    sheetData.push(rowData);
    //行数据置空
    rowData = [];
    for (var i = -2; i < dateSizeInit; i++) {
        if(i < 0){
            rowData.push(null);
        }else{
            rowData.push(columns[i].title);
        }
    }
    //将构建好的第三行描述列的数据放入二维数据表的二维数组中。
    sheetData.push(rowData);
    //遍历真实数据行
    for (var i = 0; i < rows.length; i++) {
        //将行数据置为空
        rowData = [];
        //处理列的数据
        rowData.push(rows[i][frozenColumns[0].field].toString());
        rowData.push(rows[i][frozenColumns[1].field].toString());
        for (var j = 0; j < dateSizeInit; j++) {
            if (rows[i][columns[j].field] != null) {
                rowData.push(rows[i][columns[j].field].toString());
            } else {
                rowData.push("");
            }
        }
        //一行数据加载完后往数据表格二维数组中push
        sheetData.push(rowData);
    }

    /* build worksheet from the grid data */
    var ws = XLSX.utils.aoa_to_sheet(sheetData);
    //合并单元格
    ws['!merges'] = [
        // 设置单元格合并
        {s: {r: 0, c: 0}, e: {r: 0, c: dateSizeInit + 1}},
        {s: {r: 1, c: 0}, e: {r: 2, c: 0}},
        {s: {r: 1, c: 1}, e: {r: 2, c: 1}},
        {s: {r: 1, c: 2}, e: {r: 1, c: dateSizeInit + 1}}
    ];

    /* build up workbook */
    var wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '导出数据');

    /* generate download */
    XLSX.writeFile(wb, title+".xlsx");
}

/**
 * 日期处理，小于10的在前加0
 * @param value
 * @returns {string|number}
 */
function getStrValue(value){
    var intValue = parseInt(value);
    if(intValue < 10){
        intValue = "0" + intValue;
    }else{
        intValue = "" + intValue;
    }
    return intValue;
}



